﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPPEI.Coolzon.Core;
using CPPEI.Coolzon.Core.Repositories;

namespace CPPEI.Coolzon.ManagementCenter
{
    public partial class EditUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            string Id = Request.QueryString["Id"].ToString();

            using (DbContext context = new DbContext())
            {
                IUserRepository userRepository = RepositoryFactory.Create<IUserRepository>();

                CPPEI.Coolzon.Core.Data.User user = userRepository.GetUser(context, new Guid(Id));
                txtId.Text = user.Id.ToString();
                txtAccount.Text = user.Account;
                txtName.Text = user.Name;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtAccount.Text))
                {
                    lblHint.Text = "用户名不能为空";
                    return;
                }
                else if (string.IsNullOrWhiteSpace(txtName.Text))
                {
                    lblHint.Text = "姓名不能为空";
                    return;
                }
                else if (string.IsNullOrWhiteSpace(txtPW.Text))
                {
                    lblHint.Text = "密码不能为空";
                    return;
                }
                else if (!txtPW.Text.Equals(txtPW2.Text))
                {
                    lblHint.Text = "两次密码不相同";
                    return;
                }

                CPPEI.Coolzon.Core.Data.User user = new CPPEI.Coolzon.Core.Data.User();
                user.Id = new Guid(txtId.Text);
                user.Account = txtAccount.Text;
                user.Name = txtName.Text;
                user.Password = txtPW.Text;

                using (DbContext context = new DbContext())
                {
                    IUserRepository userRepository = RepositoryFactory.Create<IUserRepository>();
                    if (userRepository.UpdateUser(context, user))
                    {
                        lblHint.Text = "修改成功";
                        Response.Redirect("UserList.aspx", false);
                    }
                    else
                    {
                        lblHint.Text = "修改失败";
                    }
                }
            }
            catch (Exception ex)
            {
                lblHint.Text = "修改失败;" + ex.Message;
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx", false);
        }
    }
}